<template>
  <el-select
    v-model="Model"
    v-bind="$attrs"
    v-on="$listeners"
    style="width: -webkit-fill-available"
    @clear="clear"
    clearable
    :placeholder="placeholder"
  >
    <template #empty>
      <div style="margin: 10px; width: -webkit-fill-available">
        <EvForm
          v-bind="$attrs"
          ref="dataSourceForm"
          :autoWidth="false"
          :itemStyle="{ marginRight: '2%', marginBottom: '10px', width: '95%' }"
          @autoEmit="autoEmit"
        >
        </EvForm>
        <EvTable
          :options="tableOptions"
          :tablePage="page"
          :showCount="false"
          @changeEvent="handleModelChange"
          @handlePageChange="handlePageChange"
          ref="EvTable"
        >
        </EvTable>
      </div>
    </template>
  </el-select>
</template>

<script>
export default {
  props: {
    value: {
      type: [String, Number, Array],
    },
    columns: {
      type: Array,
      default: () => [],
    },
    fieldValue: {
      required: true,
      type: String,
    },
    fieldLabel: {
      required: true,
      type: String,
    },
    fieldLock: {
      type: Array,
      default: () => [],
    },
    microservices: {
      required: true,
      type: String,
      default: "",
    },
    resource: {
      required: true,
      type: String,
      default: "",
    },
    filterOptions: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: "",
    },
    modelCustom: {
      type: Object,
      default: () => {
        return {
          modelField: [],
          modelRule: () => {},
        };
      },
    },
  },
  data() {
    return {
      selectedModel: this.value,
      Model: "",
      selectedValue: null,
      page: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      searchQueries: {},
      data: [],
      setRadioRow: {},
    };
  },
  async mounted() {
    await this.loadData();
    this.getCustomModel();
  },
  beforeDestroy() {
    this.clearData();
  },
  watch: {
    value() {
      this.getCustomModel();
      this.setRadio();
    },
    searchQueries() {
      this.page.currentPage = 1;
    },
    // 监听内部值的变化，更新父组件的值
    selectedModel(newVal) {
      this.$emit("input", newVal);
    },
  },
  computed: {
    tableOptions() {
      return {
        data: this.computedOptions,
        columns: this.columns,
        height: "305px",
        toolbarConfig: {
          custom: false,
          slots: {
            buttons: "toolbar_buttons",
          },
        },
        radioConfig: {
          checkMethod: this.checkMethod,
          trigger: "row",
        },
      };
    },
    computedOptions() {
      let filteredOptions = JSON.parse(JSON.stringify(this.data));

      this.filterOptions.forEach((filter) => {
        const { model, value } = filter;
        const searchValue = value.trim().toLowerCase();
        filteredOptions = filteredOptions.filter((option) => {
          return String(this.getValueFromObject(option, model)).toLowerCase().includes(searchValue);
        });
      });

      this.$attrs.dataSourceFormOptions.dataSourceFormItems.forEach((item) => {
        const { model } = item;
        const value = this.getValueByModel(model);
        if (value.trim() !== "") {
          const searchValue = value.trim().toLowerCase();
          filteredOptions = filteredOptions.filter((option) => {
            return String(this.getValueFromObject(option, model)).toLowerCase().includes(searchValue);
          });
        }
      });

      // 根据分页信息对 options 进行分页
      const start = (this.page.currentPage - 1) * this.page.pageSize;
      const end = start + this.page.pageSize;
      this.updateTotal(filteredOptions.length);
      return filteredOptions.slice(start, end);
    },
  },
  methods: {
    getCustomModel() {
      // 确保数据已经加载完成
      if (!this.data || this.data.length === 0) {
        return;
      }
      const selectedItem = this.data.find((item) => this.getValueFromObject(item, this.fieldValue) === this.value);

      if (!selectedItem) {
        return;
      }

      let modelFieldObj = {};
      this.modelCustom.modelField.forEach((item) => {
        const label = this.getValueFromObject(selectedItem, item);
        modelFieldObj[item] = label;
      });

      // 调用用户传递的 modelRule 函数来生成最终的 this.Model
      this.Model = this.modelCustom.modelRule(modelFieldObj);

      if (!this.Model) {
        this.Model = this.getValueFromObject(selectedItem, this.fieldLabel);
      }
    },
    checkMethod({ row }) {
      for (let i = 0; i < this.fieldLock.length; i++) {
        if (!this.getValueFromObject(row, this.fieldLock[i])) {
          return false;
        }
      }
      return true;
    },
    clear() {
      this.$refs.EvTable.clearRadioRow();
      this.$emit("onClear");
    },
    clearData() {
      this.data = [];
    },
    setRadio() {
      this.setRadioRow = this.computedOptions?.filter(
        (item) => this.getValueFromObject(item, this.fieldValue) === this.value
      )[0];
      this.$refs.EvTable.setRadioRow(this.setRadioRow);
    },
    getValueFromObject(obj, path) {
      const keys = path.split(".");
      let value = obj;
      for (const key of keys) {
        if (value && typeof value === "object") {
          value = value[key];
        } else {
          value = undefined;
          break;
        }
      }
      return value;
    },
    getValueByModel(model) {
      const keys = model.split(".");
      let value = this.$attrs.dataSourceFormOptions.dataSourceForm;

      keys.forEach((key) => {
        // 检查是否为对象类型
        if (typeof value === "object" && value !== null) {
          value = value[key];
        } else {
          value = null;
        }
      });

      return value;
    },
    updateTotal(value) {
      this.page.total = value;
    },
    loadData() {
      return new Promise((resolve) => {
        this.$server()
          .query(this.microservices, this.resource, null, null, null, true)
          .then((response) => {
            this.page.total = response.total;
            this.data = response.list;
            this.$emit("optionSet", this.data);
            this.setRadio();
            resolve();
          })
          .catch((response) => {
            this.$message.error(response.data.message);
          });
      });
    },
    autoEmit(model, value) {
      // 存储搜索查询
      if (value.trim() === "") {
        // 如果 value 为空，则删除对应的 model
        this.$delete(this.searchQueries, model);
      } else {
        // 否则存储搜索查询
        this.$set(this.searchQueries, model, value);
      }
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage;
      this.page.pageSize = pageSize;
      this.setRadio();
    },
    handleModelChange(data) {
      const fieldValueValue = this.getValueFromObject(data, this.fieldValue);

      if (fieldValueValue !== undefined) {
        this.selectedModel = fieldValueValue;
        this.selectedValue = fieldValueValue;
      }

      this.$emit("input", this.selectedValue);
      this.$emit("change", this.selectedValue);
      this.$emit("selectData", data);
    },
  },
};
</script>
